package com.cuit.xsc.weishare.services;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import weibo4android.Count;
import weibo4android.Paging;
import weibo4android.Status;
import weibo4android.Weibo;
import weibo4android.WeiboException;

import android.R.integer;
import android.R.string;

import com.cuit.xsc.weishare.model.DirectMessage;
import com.cuit.xsc.weishare.model.PrivateMsgResult;
import com.cuit.xsc.weishare.model.Statuse;
import com.cuit.xsc.weishare.model.User;
import com.cuit.xsc.weishare.model.UserInfo;
import com.cuit.xsc.weishare.model.WeiboBean;
import com.cuit.xsc.weishare.util.ConfigUtil;
import com.cuit.xsc.weishare.util.LogUtil;
import com.cuit.xsc.weishare.util.TextUtil;
import com.tencent.weibo.api.Private_API;
import com.tencent.weibo.api.Statuses_API;
import com.tencent.weibo.api.T_API;
import com.tencent.weibo.api.User_API;

public class StatusesService
{
	
	private static final int STATE_SINA = 1;
	private static final int STATE_QQ = 2;
	
	
	
	
	private UserInfo currentUser;
	//private boolean isSinaUser;
	
	private User_API uApi;
	private T_API tApi;
	private Statuses_API statuses_API;
	private Private_API private_API;
	private com.tencent.weibo.beans.OAuth qqOaAuth;
	private Weibo sinaWeibo;
	private int state;  
	public StatusesService(UserInfo currentUser)
	{
		this.currentUser = currentUser;
		
		if (currentUser.getUserType().equals(ConfigUtil.QQW))
		{
			
			qqOaAuth = new com.tencent.weibo.beans.OAuth();
			qqOaAuth.setOauth_token(currentUser.getToken());
			qqOaAuth.setOauth_token_secret(currentUser.getTokenSecret());
			statuses_API = new Statuses_API();
			private_API = new Private_API();
			tApi = new T_API();
			uApi = new User_API();
			state = STATE_QQ;
			
		}
		else if (currentUser.getUserType().equals(ConfigUtil.SINAW))
		{
			
			System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
	    	System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
			sinaWeibo = new Weibo();
			sinaWeibo.setOAuthAccessToken(currentUser.getToken(), currentUser.getTokenSecret());
			sinaWeibo.setOAuthConsumer(ConfigUtil.sina_AppKey, ConfigUtil.sina_AppSecret);
			state = STATE_SINA;
		}
	}
	
	
	public User getUser()
	{
		User user = null;
		switch (state)
		{
		case STATE_QQ:
			user = getQQUser();
			break;
		case STATE_SINA:
			user = getSinaUser();
			break;
		default:
			break;
		}
		
		
		
		return user;
	}
	
	
	private User getSinaUser()
	{
		User user = null;
		
		try
		{
			weibo4android.User sinaUser = sinaWeibo.showUser(currentUser.getUserId());
			if (sinaUser != null)
			{
				user = new User();
				//user.setEmail();
				user.setFavouritesCount(sinaUser.getFavouritesCount());
				user.setFollowersCount(sinaUser.getFollowersCount());
				user.setFriendsCount(sinaUser.getFriendsCount());
				user.setGender(sinaUser.getGender());
				user.setHead(sinaUser.getProfileImageURL().toString());
				user.setLocation(sinaUser.getLocation());
				user.setName(sinaUser.getName());
				user.setStatusesCount(sinaUser.getStatusesCount());
				user.setVip(sinaUser.isVerified());
			}
		}
		catch (WeiboException e)
		{
			e.printStackTrace();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		
		
		return user;
	}
	
	private User getQQUser()
	{
		User user = null;
		
		try
		{
			String result = uApi.info(qqOaAuth, "json");
			LogUtil.i(this, "user result:"+result);
			
			JSONObject jsonObject = new JSONObject(result);
			if ((jsonObject.getInt("ret")==0) && !jsonObject.isNull("data") )
			{
				JSONObject jobject = jsonObject.getJSONObject("data");
				user = new User(jobject);
			}
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		
		
		
		return user;
	}
	
	
	
	
	public Map<String,List<DirectMessage>> recvPivateMessage()
	{
		Map<String,List<DirectMessage>> list = null;
		String result = null;
		switch (state)
		{
		case STATE_QQ:
			//result = statuses_API.home_timeline(qqOaAuth, "json", pageflag, pagetime, reqnum, "3", "0");
			try
			{
				result = private_API.recv(qqOaAuth, "json", "0", "0", "20");
				System.out.println("recv_msg:"+result);
				list = resoveDirectMsg(list, DirectMessage.RECV, result);
				
				result = private_API.send(qqOaAuth, "json", "0", "0", "20");
				System.out.println("send_msg:"+result);
				list = resoveDirectMsg(list, DirectMessage.SEND, result);
			} 
			catch (Exception e)
			{
				e.printStackTrace();
			}
			break;
		case STATE_SINA:
			
			break;

		default:
			break;
		}
		return list;
	}
	
	public List<Statuse> getFriendsTimeline()
	{
		List<Statuse> list = null;
		
		switch (state)
		{
		case STATE_QQ:
			list = getQQFriendsTimeline("0", "0", "20");
			break;
		case STATE_SINA:
			Paging page = new Paging(1, 20);
			list = getSinaFriendsTimeline(page);
			break;
		default:
			break;
		}
		
		return list;
		
		
	}
	
	
	
	public List<Statuse>  getNewTimeLine(long pagetime)
	{
		List<Statuse> list = null;
		
		switch (state)
		{
		case STATE_QQ:
			list = getQQFriendsTimeline("2", pagetime+"", "1");
			break;
		case STATE_SINA:
			Paging page = new Paging(1, 10);
			page.setSinceId(pagetime);
			list = getSinaFriendsTimeline(page);
			break;
		default:
			break;
		}
		
		
		return list;
		
	}
	
	
	public List<Statuse> getOldTimeLine(long pagetime)
	{
		
      List<Statuse> list = null;
		
		switch (state)
		{
		case STATE_QQ:
			list = getQQFriendsTimeline("1", pagetime+"", "10");
			break;
		case STATE_SINA:
			Paging page = new Paging(1, 10);
			page.setMaxId(pagetime);
			list = getSinaFriendsTimeline(page);
			if (list != null && !list.isEmpty())
			{
			   list.remove(0);
			}
			break;
		default:
			break;
		}
		
		return list;
		
	}
	
	
	public PrivateMsgResult publishPrivateMsg(String name, String content)
	{
		PrivateMsgResult resultMsg = null;
		switch (state)
		{
		case STATE_QQ:
			try
			{
			 String result = private_API.add(qqOaAuth, "json", content, "127.0.0.1", name);
			 
			 if (result != null)
				{
					JSONObject jsonObject = new JSONObject(result);
					if ((jsonObject.getInt("ret")==0) && !jsonObject.isNull("data") )
					{
					 JSONObject data =	jsonObject.getJSONObject("data");
					 resultMsg = new PrivateMsgResult(data);
					}
				}
			 
			 
			}
			catch (Exception e)
			{
				resultMsg = null;
				e.printStackTrace();
			}
		case STATE_SINA:
			
			break;
		default:
			break;
		}
		
		return resultMsg;
	}
	
	public int publishWeibo(WeiboBean weiboBean)
	{
		int result = -1;
		String imgUrl = weiboBean.getIconUrl();
		switch (state)
		{
		case STATE_QQ:
			
			try
			{
				if (imgUrl == null)
				{
					tApi.add(qqOaAuth, "json", weiboBean.getText(), "127.0.0.1", "", "");
				}
				else 
				{
					tApi.add_pic(qqOaAuth, "json", weiboBean.getText(), "127.0.0.1", weiboBean.getIconUrl());
				}
				
				result = 1;
			} 
			catch (Exception e)
			{
				e.printStackTrace();
			}
			break;
		case STATE_SINA:
			
			try
			{
				if (imgUrl == null)
				{
					sinaWeibo.updateStatus(weiboBean.getText());
				}
				else
				{
					File file = new File(weiboBean.getIconUrl());
					sinaWeibo.uploadStatus(weiboBean.getText(), file);
				}
				
				result = 1;
			} 
			catch (WeiboException e)
			{
				e.printStackTrace();
			}
			
			break;
		default:
			break;
		}
		return result;
	}
	
	private List<Statuse> getQQFriendsTimeline(String pageflag, String pagetime, String reqnum)
	{
		List<Statuse> list = null;
		String result = null;
		try
		{
			result = statuses_API.home_timeline(qqOaAuth, "json", pageflag, pagetime, reqnum, "3", "0");
			
			if (result != null)
			{
				JSONObject jsonObject = new JSONObject(result);
				if ((jsonObject.getInt("ret")==0) && !jsonObject.isNull("data") )
				{
					list = new ArrayList<Statuse>();
					JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("info");
					int len = jsonArray.length();
					for (int i = 0; i < len; i++)
					{
						JSONObject jObject = jsonArray.getJSONObject(i);
						//LogUtil.e(this, "weibo id:"+jObject.getLong("id"));
						Statuse statuse = new Statuse(jObject);
						list.add(statuse);
					}
				}
			}
			
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
	//	LogUtil.i(this, "qq_status:"+list);
		
		return list;
	}
	
	private List<Statuse> getSinaFriendsTimeline(Paging page)
	{
		
		
		List<Statuse> list = null;
		List<Status> status = null;
		try
		{
			status= sinaWeibo.getFriendsTimeline(page);
			if (status != null && !status.isEmpty())
			{
				list = new ArrayList<Statuse>();
				for (Status s : status)
				{

					Statuse statuse = new Statuse();
					statuse.setId(s.getId());
					statuse.setHead(s.getUser().getProfileImageURL().toString());
					statuse.setuName(s.getUser().getName());
					statuse.setVerified(s.getUser().isVerified());
					statuse.setTime(TextUtil.formatDate(s.getCreatedAt()));
					statuse.setContent(s.getText());
					statuse.setContent_pic(s.getThumbnail_pic());
					statuse.setFrom(s.getSource());
					statuse.setRedirect(s.getRepostsCount());
					statuse.setComment(s.getCommentsCount());
					if(s.getRetweeted_status()!=null)
					{
						Statuse subStatuse = new Statuse();
						subStatuse.setContent(s.getRetweeted_status().getText());
						subStatuse.setContent_pic(s.getRetweeted_status().getThumbnail_pic());
						statuse.setStatuse(subStatuse);
					}
					list.add(statuse);
				}
			}
		}
		catch (WeiboException e)
		{
			e.printStackTrace();
		}
		
		return list;
		
	}
	
	
	
	private Map<String, List<DirectMessage>> resoveDirectMsg(Map<String, List<DirectMessage>> map, int type ,String json)
	{
		if (map == null)
		{
			map = new HashMap<String, List<DirectMessage>>();
		}
		
		if (json != null)
		{
			try
			{
				JSONObject jsonObject = new JSONObject(json);
				if ((jsonObject.getInt("ret")==0) && !jsonObject.isNull("data") )
				{
					JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("info");
					int len = jsonArray.length();
					for (int i = 0; i < len; i++)
					{
						JSONObject jObject = jsonArray.getJSONObject(i);
						DirectMessage directMessage = new DirectMessage(type, jObject);
						if (directMessage != null)
						{
							String key = null;
							if (type == DirectMessage.RECV)
							{
								key = directMessage.getName();
							}
							else if (type == DirectMessage.SEND) 
							{
								key = directMessage.getToname();
							}
						   
							List<DirectMessage> directMessages = map.get(key);
							if (directMessages == null)
							{
								directMessages = new ArrayList<DirectMessage>();
								map.put(key, directMessages);
							}
							directMessages.add(directMessage);
						}
					}
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}

		return map;
	}


	
	
	
	
	

}
